<template>
	<view :class="['container',$store.state.theme.themeType]"
		:style="{'height':'calc(100vh - var(--status-bar-height))','padding-top': 'var(--status-bar-height)','--nav_color':$store.state.theme.navColor,'--background':$store.state.theme.background,'--color1':$store.state.theme.color1,'--color2':$store.state.theme.color2}">
		<view class="nav">
			<view @click="back()" class="iconfont icon-gengduo" style="transform: rotateZ(180deg);">
			</view>
			<view v-if="selectList.length" style="font-size: 30rpx;" @click="startImport">
				确定({{selectList.length}}本)
			</view>
		</view>
		<view class="main" :style="{'height':'calc(100vh - var(--status-bar-height) - 56px)'}">
			<view v-for="(item,index) in List" :class="['item',selectList.indexOf(item.path)>-1?'active':null]"
				:key="index" @click="select(item)">
				<view class="right">
					<image src="../../static/files-icon/txt.png" style="width: 100rpx;height: 100rpx;"></image>
				</view>
				<view class="left">
					<view
						style="width: calc(100vw - 200rpx);padding:10rpx 0rpx 10rpx 20rpx;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;font-size: 30rpx;">
						{{item.name}}
					</view>
					<view
						style="width: calc(100vw - 200rpx);padding:10rpx 0rpx 10rpx 20rpx;font-size: 24rpx; color: var(--color-second);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
						{{item.time|dateFormat}} - {{item.size}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	//#ifdef APP
	var ChiMoudle = uni.requireNativePlugin("ChiMoudle")
	//#endif
	export default {
		filters: {
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "/" + month + "/" + day;
			},
		},
		data() {
			return {
				List: [],
				selectList: []
			};
		},
		onLoad() {
			//#ifdef APP
			var globalEvent = uni.requireNativePlugin('globalEvent')
			globalEvent.addEventListener('getTXT', e => {
				this.List = this.List.concat(e.list)
				this.List.sort(function(a, b) {
					return b.time - a.time
				})
			})
			this.start()
			//#endif
		},
		onShow() {
			//#ifdef APP
			plus.navigator.setStatusBarStyle(this.$store.state.theme.themeType == 'dark' ? 'light' : 'dark');
			//#endif

		},
		onReady() {
			//#ifdef APP
			plus.navigator.setStatusBarStyle(this.$store.state.theme.themeType == 'dark' ? 'light' : 'dark');
			//#endif
		},
		methods: {
			startImport() {
				let startt = new Date().getTime()
				let tasks = this.selectList.map(i => {
					return {
						func: this.work,
						path: i
					}
				})

				let t = tasks.length
				uni.showLoading({
					mask: true,
					title: "剩余" + t + "本"
				})
				Promise.all(Array.from({
					length: 4
				}).map((i, j) => {
					return new Promise((resolve, reject) => {
						function run() {
							if (tasks.length <= 0) {
								resolve()
								return
							}
							let task = tasks.shift()
							task.func(task.path).then(_ => {
								t--
								uni.showLoading({
									mask: true,
									title: "剩余" + t + "本"
								})
								run()
							})
						}
						run()
					})
				})).then(res => {
					uni.navigateBack()
					uni.hideLoading()
				})
			},
			work(path) {
				let that = this
				return new Promise(resolve => {
					plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
						fs.root.getFile("file://" + path, {
							create: false
						}, function(fileEntry) {
							fileEntry.file(function(file) {
								var fileReader = new plus.io.FileReader();
								let name = file.name
								fileReader.readAsText(file, 'utf-8');
								fileReader.onloadend = function(evt) {
									let char = evt.target.result.split('\n')
									let num = 0

									let save = {
										chapters: [],
										info: {
											name: name,
											author: "本地导入",
											image: ""
										},
										status: 1,
										time: new Date().getTime(),
										current: 0,
										currentchapters: 0,
									}
									let o = {
										name: null,
										content: "",
										num: 0
									}

									for (let s of char) {
										if (s[0] == '　' && s[1] == '　') {
											o.content = o.content + s + '\n'
										} else {
											if (o.content&&o.name) {
												save.chapters.push(o)
												num++
												o = {
													name: null,
													content: "",
													num: num
												}
											}
											o.name = s
										}
									}
									uni.setStorage({
										key: 'novel_' + name + "_本地导入",
										data: save
									})
									let a = JSON.parse(JSON.stringify(save.info))
									a.time = save.time
									a.currentchapters = save.currentchapters + 1
									a.total = save.chapters.length
									a.status = 1
									a.lastestchapter = save.chapters[save.chapters
										.length - 1].name
									that.$store.commit("data/ADD_NOVELLIST", a)
									resolve()
								}
							});
						});
					});

				}).catch(e => {
					console.log(e);
				})
			},
			select(item) {
				let index = this.selectList.indexOf(item.path)
				if (index > -1) {
					this.selectList.splice(index, 1)
				} else {
					this.selectList.push(item.path)
				}
			},
			start() {
				if (!ChiMoudle) {
					uni.showToast({
						icon: 'none',
						title: "插件执行失败"
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: "文件搜索中"
					})
				}
				ChiMoudle.getAllTXT({}, e => {
					uni.showToast({
						title: "搜索完成",
						icon: 'none'
					})
				})
			},
			back() {
				uni.navigateBack({

				})
			}
		}
	}
</script>

<style lang="less">
	.container {
		background: var(--background);
		height: 100vh;

		.main {
			overflow-y: scroll;

			.item.active {
				color: #007aff;
				border: 2rpx dashed #007aff;
			}

			.item {
				border: 2rpx dashed rgba(0, 0, 0, 0);
				margin: 40rpx;
				display: flex;
				align-items: center;
				flex-direction: row;
				border-radius: 20rpx;
				background: var(--background);
				box-shadow: 10rpx 10rpx 15rpx var(--color1), -10rpx -10rpx 15rpx var(--color2);
			}

		}

		.nav {
			height: 56px;
			padding: 0 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: var(--background);
			box-shadow: 0rpx 10rpx 15rpx var(--color1), 0rpx 0rpx 0rpx var(--color1);

			.iconfont {
				font-size: 50rpx;
			}
		}
	}
</style>
